var lib = null;
var PAGE_CHANGE_MODEL=VERTICAL; // HORIZONTAL, VERTICAL

// 获取下一页
const PAGE_EVENT_GETPAGENUM = "page_event_getpagenum";
const pageData = {
    page_1: {
        resourceImgs: [
            // {src:"images/icon1.png", id:"icon1", mc_path:["sig_dlg/dlg/mc_icon/icon1", "sig_dlg/dlg/mc_icon/icon1"]},
        ]
    },
    page_2: {
        resourceImgs: []
    },
    page_3: {
        resourceImgs: []
    },
}

const fontFamily = '-apple-system, BlinkMacSystemFont, "PingFang SC","Helvetica Neue",STHeiti,"Microsoft Yahei",Tahoma,Simsun,sans-serif';

let that = {
    create_text: null
};

let selectFrameIdx = 0;
let currMap = null;
let currTypeMc = null;
let InformedConsent = false;

function onPageInited(e) {
    var page = e.page.page;
    page.data = pageData["page_"+e.pageId];

    that.create_text = createjs.Text;
    let question_text = QuestionText();
    createjs.Text = question_text.Text;

    console.log("##", e);

    // if(page.mc_floor) {
    //     page.mc_floor.y=lib.properties.height;
    // }
    //
    // if(page.pt_mc) {
    //     page.pt_mc.y=lib.properties.height-50;
    // }
    //
    // if(page.pt_mc1) {
    //     page.pt_mc1.y=lib.properties.height-50;
    // }

    switch (e.pageId) {
        case 1: {
            // page.mc.mc.contentSizeMc.alpha = 0;
            // page.mc.mc.contentSizeMc.visible = false;
            // page.mc.mc.contentSizeMc.mouseEnabled = false;

            let share = getQueryVariable("share");
            if (share){
                getHelpStatus({code:share}, (res)=>{
                    if (res.errcode == 0){
                        // 助力
                        openDlg(1, (data)=>{
                            if(data.enter) {
                                help({code:share}, (res)=>{
                                    if (res.errcode == 0){
                                        // 助力成功
                                        openDlg(2);
                                    }else {
                                        vant.showToast(res.errmsg)
                                    }
                                })
                            }
                        });
                    }else {
                        vant.showToast(res.errmsg)
                    }
                })
            }else {
                //未找到share字段
                console.log("未找到share字段")
            }

            // 进度显示
            // openDlg(3);

            init_scroll(page.mc, {x:0, y:0, width:lib.properties.width, height:lib.properties.height}, page.mc.mc.bg);

            let checkAnimations = ()=>{
                if(page.mc.mc.btn1.currentFrame<=0) {
                    let y = (page.mc.mc.btn1.y + page.mc.mc.btn1.getTransformedBounds().height)/stage.scaleY;
                    let x = page.mc.mc.btn1.x;

                    let pt = page.mc.mc.localToGlobal(x, y);

                    if(pt.y<lib.properties.height) {
                        page.mc.mc.btn1.gotoAndPlay(1)
                    }
                }

                if(page.mc.mc.btn2.currentFrame<=0) {
                    let y = (page.mc.mc.btn2.y + page.mc.mc.btn2.getTransformedBounds().height)/stage.scaleY;
                    let x = page.mc.mc.btn2.x;

                    let pt = page.mc.mc.localToGlobal(x, y);

                    if(pt.y<lib.properties.height) {
                        page.mc.mc.btn2.gotoAndPlay(1)
                    }
                }

                if(page.mc.mc.btn3.currentFrame<=0) {
                    let y = (page.mc.mc.btn3.y + page.mc.mc.btn3.getTransformedBounds().height)/stage.scaleY;
                    let x = page.mc.mc.btn3.x;

                    let pt = page.mc.mc.localToGlobal(x, y);

                    if(pt.y<lib.properties.height) {
                        page.mc.mc.btn3.gotoAndPlay(1)
                    }
                }

                // if(page.mc.mc.mc1.currentFrame<=0) {
                //     let y = (page.mc.mc.mc1.y + page.mc.mc.mc1.getTransformedBounds().height)/stage.scaleY;
                //     let x = page.mc.mc.mc1.x;
                //
                //     let pt = page.mc.mc.localToGlobal(x, y);
                //
                //     console.log(pt.y, lib.properties.height)
                //
                //     if(pt.y<lib.properties.height) {
                //         page.mc.mc.mc1.gotoAndPlay(1)
                //     }
                // }
            }

            let checkMcTarget = ()=>{
                console.log("### checkMcTarget");
                if(page.mc.mc.btn1.opened && page.mc.mc.btn2.opened && page.mc.mc.btn3.opened) {
                    page.mc.mc.mc1.gotoAndPlay(1);

                    let height = page.mc.mc.mc1.y+page.mc.mc.mc1.getTransformedBounds().height+200;
                    let scale = height/page.mc.mc.bg.getBounds().height;

                    page.mc.mc.bg.scaleY = scale;
                }
            }

            page.mc.mc.btn1.addEventListener("checkMcTarget", checkMcTarget);
            page.mc.mc.btn2.addEventListener("checkMcTarget", checkMcTarget);
            page.mc.mc.btn3.addEventListener("checkMcTarget", checkMcTarget);

            let onUpdateMC = (name)=>{
                let moveMc=null;
                let y=0;

                switch (name) {
                    case "btn1": {
                        page.mc.mc.btn1.opened = true;
                        y = page.mc.mc.btn1.y + 920;
                        moveMc = page.mc.mc.btn2;
                        break;
                    }
                    case "btn2": {
                        page.mc.mc.btn2.opened = true;
                        y = page.mc.mc.btn2.y + 920;
                        moveMc = page.mc.mc.btn3;
                        break;
                    }
                    case "btn3": {
                        page.mc.mc.btn3.opened = true;
                        y = page.mc.mc.btn3.y + 920;
                        moveMc = page.mc.mc.mc1;
                        break;
                    }
                }

                createjs.Tween.get(moveMc, {override:true}).to({y:y}, 400).addEventListener("change", (event)=>{
                    switch (name) {
                        case "btn1": {
                            page.mc.mc.btn3.y = moveMc.y+moveMc.getTransformedBounds().height;
                            page.mc.mc.mc1.y = page.mc.mc.btn3.y+page.mc.mc.btn3.getTransformedBounds().height;
                            break;
                        }
                        case "btn2": {
                            page.mc.mc.mc1.y = moveMc.y+moveMc.getTransformedBounds().height;
                            break;
                        }
                        case "btn3": {

                            break;
                        }
                    }

                    // let height = page.mc.mc.mc1.y+page.mc.mc.mc1.getTransformedBounds().height+200;
                    let height = page.mc.mc.mc1.y+200;
                    let scale = height/page.mc.mc.bg.getBounds().height;

                    page.mc.mc.bg.scaleY = scale;
                })
            }

            page.group_btn.btn_my.addEventListener("click", e=>{
                openPage(4);
            });
            page.group_btn.btn_rule.addEventListener("click", e=>{
                console.log("## open rule dlg");
            });

            page.mc.mc.btn1.addEventListener("complate", e=>{
                let y = (page.mc.mc.btn1.y + page.mc.mc.btn1.getTransformedBounds().height)/stage.scaleY;
                let x = page.mc.mc.btn1.x;

                let pt = page.mc.mc.localToGlobal(x, y);

                if(pt.y<lib.properties.height) {
                    page.mc.mc.btn1.gotoAndPlay(1)
                }
            })
            page.mc.mc.btn2.addEventListener("complate", e=>{
                let y = (page.mc.mc.btn2.y + page.mc.mc.btn2.getTransformedBounds().height)/stage.scaleY;
                let x = page.mc.mc.btn2.x;

                let pt = page.mc.mc.localToGlobal(x, y);

                if(pt.y<lib.properties.height) {
                    page.mc.mc.btn2.gotoAndPlay(1)
                }
            })
            page.mc.mc.btn3.addEventListener("complate", e=>{
                let y = (page.mc.mc.btn3.y + page.mc.mc.btn3.getTransformedBounds().height)/stage.scaleY;
                let x = page.mc.mc.btn3.x;

                let pt = page.mc.mc.localToGlobal(x, y);

                if(pt.y<lib.properties.height) {
                    page.mc.mc.btn3.gotoAndPlay(1)
                }
            })
            page.mc.mc.mc1.addEventListener("complate", e=>{
                // let y = (page.mc.mc.mc1.y + page.mc.mc.mc1.getTransformedBounds().height)/stage.scaleY;
                // let x = page.mc.mc.mc1.x;
                //
                // let pt = page.mc.mc.localToGlobal(x, y);
                //
                // if(pt.y<lib.properties.height) {
                //     page.mc.mc.mc1.gotoAndPlay(1)
                // }
            })

            page.mc.mc.btn1.addEventListener("click", e => {
                if(page.mc.mc.btn1.opened) return;

                page.mc.mc.btn1.gotoAndPlay("open");
                onUpdateMC("btn1");
            });

            page.mc.mc.btn2.addEventListener("click", e => {
                if(page.mc.mc.btn2.opened) return;

                page.mc.mc.btn2.gotoAndPlay("open");
                onUpdateMC("btn2");
            });

            page.mc.mc.btn3.addEventListener("click", e => {
                if(page.mc.mc.btn3.opened) return;

                page.mc.mc.btn3.gotoAndPlay("open");
                onUpdateMC("btn3");
            });

            page.mc.mc.mc1.addEventListener("click", e => {
                let pt = {x: e.stageX/pRatio/sRatio*stage.scaleX, y: e.stageY/pRatio/sRatio*stage.scaleY};
                let pt_ = page.mc.mc.mc1.localToGlobal(page.mc.mc.mc1.enter_btn.x, page.mc.mc.mc1.enter_btn.y);

                if(pt.x>pt_.x&&pt.x<pt_.x+page.mc.mc.mc1.enter_btn.getTransformedBounds().width*stage.scaleX) {
                    if(pt.y>pt_.y&&pt.y<pt_.y+page.mc.mc.mc1.enter_btn.getTransformedBounds().height*stage.scaleY){
                        // 抽奖
                        console.log("抽奖");
                        // checkLottery((checkLotteryRes)=>{
                        //     if (checkLotteryRes.errcode == 0){
                        //         if (checkLotteryRes.count == 0){
                        //             // 正常抽奖机会已用完
                        //             if (!checkLotteryRes.isHelp){
                        //                 // 没有收到助力
                        //
                        //             }else {
                        //                 // 已收到过助力，不再通过分享增加抽奖机会
                        //                 openPage(3);
                        //                 page.gotoAndPlay("f2");
                        //             }
                        //
                        //         }else {
                        //             openDlg(3);
                        //             lottery((res)=>{
                        //                 if (res.errcode == 0){
                        //                     // 抽奖成功
                        //                     closeDlg();
                        //                     if (res.isLottery){
                        //                         // 中奖
                        //
                        //                     }else {
                        //                         // 未中奖
                        //                         openPage(3);
                        //                     }
                        //
                        //                 }else {
                        //                     closeDlg();
                        //                     vant.showToast(res.errmsg)
                        //                 }
                        //             })
                        //         }
                        //     }else {
                        //         vant.showToast(checkLotteryRes.errmsg)
                        //     }
                        // })

                        openDlg(3);

                        setTimeout(()=>{
                            closeDlg();
                            openPage(3);
                        }, 3000);
                    }
                }
            });

            page.mc.addEventListener(EVENT_SCROLL_START, e => {
                console.log("page.mc scroll start")
            })

            page.mc.addEventListener(EVENT_SCROLL_CHANGE, e => {
                checkAnimations();
            })

            page.mc.addEventListener(EVENT_SCROLL_FINISH, e => {
                console.log("page.mc scroll finish", page.mc.mc.btn1.currentFrame)
            })

            e.page.addEventListener("mousedown", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressmove", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressup", e => {
                e.stopPropagation();
            });
            break;
        }
        case 2: {

            page.mc.form.addEventListener("complate", e => {
                console.log("## form complate")

                let pt = page.mc.form.localToGlobal(page.mc.form.txt_name.x, page.mc.form.txt_name.y);

                let width = page.mc.form.txt_name.getTransformedBounds().width;
                let height = page.mc.form.txt_name.getTransformedBounds().height;
                let size = page.mc.form.localToGlobal(page.mc.form.txt_name.x+width, page.mc.form.txt_name.y+height);

                App.user.name.show = true;
                App.user.name.left = pt.x/stage.scaleX/canvasScale;
                App.user.name.top = pt.y/stage.scaleX/canvasScale;
                App.user.name.width = (size.x-pt.x)/stage.scaleX/canvasScale;
                App.user.name.height = (size.y-pt.y)/stage.scaleX/canvasScale;

                pt = page.mc.form.localToGlobal(page.mc.form.txt_phone.x, page.mc.form.txt_phone.y);

                width = page.mc.form.txt_phone.getTransformedBounds().width;
                height = page.mc.form.txt_phone.getTransformedBounds().height;
                size = page.mc.form.localToGlobal(page.mc.form.txt_phone.x+width, page.mc.form.txt_phone.y+height);

                App.user.phone.show = true;
                App.user.phone.left = pt.x/stage.scaleX/canvasScale;
                App.user.phone.top = pt.y/stage.scaleX/canvasScale;
                App.user.phone.width = (size.x-pt.x)/stage.scaleX/canvasScale;
                App.user.phone.height = (size.y-pt.y)/stage.scaleX/canvasScale;

                pt = page.mc.form.localToGlobal(page.mc.form.txt_addres.x, page.mc.form.txt_addres.y);

                width = page.mc.form.txt_addres.getTransformedBounds().width;
                height = page.mc.form.txt_addres.getTransformedBounds().height;
                size = page.mc.form.localToGlobal(page.mc.form.txt_addres.x+width, page.mc.form.txt_addres.y+height);

                App.user.address.show = true;
                App.user.address.left = pt.x/stage.scaleX/canvasScale;
                App.user.address.top = pt.y/stage.scaleX/canvasScale;
                App.user.address.width = (size.x-pt.x)/stage.scaleX/canvasScale;
                App.user.address.height = (size.y-pt.y)/stage.scaleX/canvasScale;
            });

            e.page.addEventListener("mousedown", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressmove", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressup", e => {
                e.stopPropagation();
            });
            break;
        }
        case 3: {
            // 未中奖
            // page.gotoAndStop("f1");
            // 抽奖机会已用完
            // page.gotoAndStop("f2");
            // 中奖
            page.gotoAndStop("f3");

            e.page.addEventListener("mousedown", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressmove", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressup", e => {
                e.stopPropagation();
            });
            break;
        }
        case 4: {
            // 未中奖
            // page.gotoAndStop("f1");
            // 中奖1次
            // page.gotoAndStop("f2");
            // 中奖2次
            page.gotoAndStop("f3");

            e.page.addEventListener("mousedown", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressmove", e => {
                e.stopPropagation();
            });
            e.page.addEventListener("pressup", e => {
                e.stopPropagation();
            });
            break;
        }
    }
}

function pageUpdated(e) {
    let page = e.page.page;

    let onScrollPage = ()=>{
        onScrollMc(page.mv, (offsetX, offsetY, touchPt, params)=>{
            let touchEndStart = false;
            let touchEndEnd = false;

            let _y=offsetY;
            let screenHeight = lib.properties.height;

            if(page.mv.y+offsetY>0) {
                offsetY = -page.mv.y;
                touchEndStart = true;
            } else {
                touchEndStart = false;
            }

            if((page.mv.y+page.mv.getTransformedBounds().height+offsetY)<screenHeight) {
                offsetY = screenHeight-(page.mv.y+page.mv.getBounds().height);
                touchEndEnd = true;
            } else {
                touchEndEnd = false;
            }

            switch (e.pageId) {
                case 4: {
                    page.mv.y+=offsetY;
                    break;
                }
                default:{
                    page.mv.y+=offsetY;
                }
            }

            if(touchEndStart||touchEndEnd) {
                if(!page.dispatchEventMousedown&&touchPt) {
                    var event = new createjs.Event("mousedown");

                    if(params.state=="pressmove"&&_y!=0) {
                        exportRoot.main.dispatchEvent(event);
                        page.dispatchEventMousedown = true;
                    }
                }
            }
        });
    }

    switch (e.pageId) {
        case 1: {
            page.gotoAndPlay(1);
            return;
        }
        case 2:{
            page.gotoAndPlay(1);
            // 留资
            page.mc.gotoAndPlay("f1");
            // 展示兑换码
            // page.mc.gotoAndPlay("f3");

            // 提交留资
            page.mc.btn_enter.addEventListener("click", e => {
                // ..

                // 留资成功
                App.user.name.show = false;
                App.user.phone.show = false;
                App.user.address.show = false;
                page.mc.gotoAndPlay("f2");
            });

            page.mc.btn_back.addEventListener("click", e => {
                openPage(1, {prev: true});
            });
            break;
        }
        case 3:{
            // 未中奖
            page.gotoAndPlay("f1");
            // 抽奖机会已用完
            // page.gotoAndPlay("f2");
            // 中奖
            // page.gotoAndPlay("f3");
            //

            page.view3.addEventListener("gift_complate", e => {
                console.log("===gift_complate===");

                // 往返机票
                // page.view3.gift_box.mc.gift.gotoAndStop("f1");
                // 迪士尼门票
                page.view3.gift_box.mc.gift.gotoAndStop("f2");
            });

            let onOpenShareDlg = ()=>{
                // page.share_dlg.bg.scaleY = lib.properties.height/page.share_dlg.bg.getBounds().height;
                // page.share_dlg.gotoAndPlay(1);
                openDlg(4);
            };

            page.view1.btn_share.addEventListener("click", e => {
                onOpenShareDlg();
            });

            page.view2.btn_back.addEventListener("click", e => {
                openPage(1, {prev: true});
            });
            page.view2.btn_share.addEventListener("click", e => {
                onOpenShareDlg();
            });

            page.view3.btn_share1.addEventListener("click", e => {
                onOpenShareDlg();
            });
            page.view3.btn_share2.addEventListener("click", e => {
                onOpenShareDlg();
            });
            page.share_dlg.btn_close.addEventListener("click", e => {
                page.share_dlg.gotoAndStop(0);
            })
            break;
        }
        case 4:{
            // 未中奖
            // page.gotoAndPlay("f1");
            // 中奖1次
            // page.gotoAndPlay("f2");
            // 中奖2次
            page.gotoAndPlay("f3");

            page.view1.mc1.btn_share.addEventListener("click", e => {
                console.log("## share")
            });

            page.view1.mc2.btn_back.addEventListener("click", e => {
                openPage(1, {prev: true});
            });

            page.view2.mc1.btn_share.addEventListener("click", e => {
                console.log("## share")
            });

            page.view2.mc2.btn_back.addEventListener("click", e => {
                openPage(1, {prev: true});
            });

            page.view3.mc1.btn_share.addEventListener("click", e => {
                console.log("## share")
            });

            page.view3.mc2.btn_back.addEventListener("click", e => {
                openPage(1, {prev: true});
            });

            page.view2.mc2.mc_gift.g1.addEventListener("click", e => {
                console.log("## gift1")
                openPage(2)
            });
            page.view3.mc2.mc_gift.g1.addEventListener("click", e => {
                console.log("## gift1")
                openPage(2)
            });
            page.view3.mc2.mc_gift.g2.addEventListener("click", e => {
                console.log("## gift2")
                openPage(2)
            });

            page.view1.mc1.mc_progress_bar.gotoAndStop(10);
            // page.view2.mc1.mc_progress_bar.gotoAndStop(10);
            // page.view3.mc1.mc_progress_bar.gotoAndStop(10);
            break;
        }
    }
}

function onScrollMc(mc, callback) {
    // 页面内长图滚动
    let touched = false, ticking = false;
    let startStageX=0, startStageY=0, stageX=0, stageY=0, speedX=0, speedY=0, timeStamp=0, currStageX=0, currStageY=0, currTimeStamp=0, speedUpdateTimeStamp=0;
    let pt_mc = null;

    let parentMc = mc.parent;
    let _callback = callback;

    parentMc.addEventListener("mousedown", handleStart);

    function handleStart(e) {
        touched = true;

        let pt = parentMc.globalToLocal(e.stageX, e.stageY);

        startStageX=pt.x;
        startStageY=pt.y;
        stageX = pt.x;
        stageY = pt.y;
        timeStamp = e.timeStamp;

        currStageX = startStageX;
        currStageY = startStageY;
        currTimeStamp = timeStamp;

        if(!parentMc.getChildByName("pt_mc")) {
            pt_mc = new lib.pt();
            pt_mc.name = "pt_mc";
            parentMc.addChild(pt_mc);
            pt_mc.mouseEnabled = false;
            pt_mc.visible = false;
        } else {
            pt_mc = parentMc.getChildByName("pt_mc")
        }

        pt_mc.x = pt.x;
        pt_mc.y = pt.y;

        if(_callback) {
            let touchPt = null;

            if(touched) {
                touchPt = parentMc.globalToLocal(e.stageX, e.stageY);
                touchPt.x = currStageX;
                touchPt.y = currStageY;
            }

            _callback(0, 0, touchPt, { state: "mousedown"});
        }

        parentMc.addEventListener("pressup", handleEnd);
        parentMc.addEventListener("pressmove", handleMove);

        if(!ticking) {
            parentMc.addEventListener("tick", onScorllTick);
            ticking = true;
        }

        e.stopPropagation();
    }

    function handleMove (e) {
        let t = e.timeStamp-timeStamp;
        let pt = parentMc.globalToLocal(e.stageX, e.stageY);

        if(parentMc.dispatchEventMousedown) {
            var event = new createjs.Event("pressmove");
            event.stageX = e.stageX;
            event.stageY = e.stageY;

            exportRoot.main.dispatchEvent(e);
        } else {
            e.stopPropagation();
        }

        currStageX = pt.x;
        currStageY = pt.y;
        currTimeStamp = e.timeStamp;
    }

    function onScorllTick(e) {
        if(parentMc.dispatchEventMousedown) {
            return;
        }

        if(!touched) {
            if(Math.abs(speedY)>0) {
                speedY += -speedY/10;

                if(Math.abs(speedY)<=0.01) {
                    speedY = 0;
                }
            }

            if(Math.abs(speedX)>0) {
                speedX += -speedX/10;

                if(Math.abs(speedX)<=0.01) {
                    speedX = 0;
                }
            }

            if(Math.abs(speedY)<=0&&Math.abs(speedX)<=0) {
                ticking = false;
                parentMc.removeEventListener("tick", onScorllTick);
            }
        } else {
            let t = currTimeStamp-timeStamp;

            if(t!=0) {
                speedY = (currStageY-stageY)/t;
                speedX = (currStageX-stageX)/t;
            } else {
                speedY = 0;
                speedX = 0;
            }
        }

        stageX = currStageX;
        stageY = currStageY;
        timeStamp=currTimeStamp;

        let offsetY = speedY*e.delta;
        let offsetX = speedX*e.delta;

        // if(parentMc.mv1.y+offsetY>0) {
        //     offsetY = -parentMc.mv1.y;
        //     touchEndStart = true;
        // } else {
        //     touchEndStart = false;
        // }

        // switch (App.orientation) {
        //     case VERTICAL:{
        // 竖屏
        // if((parentMc.mv1.y+parentMc.mv1.getBounds().height+offsetY)<lib.properties.height) {
        //     offsetY = lib.properties.height-(parentMc.mv1.y+parentMc.mv1.getBounds().height);
        //     touchEndEnd = true;
        // } else {
        //     touchEndEnd = false;
        // }

        //     break;
        // }
        // case HORIZONTAL:{
        // 横屏
        // let height = lib.properties.width*lib.properties.width/lib.properties.height;
        //
        // if((parentMc.mv1.y+parentMc.mv1.getBounds().height+offsetY)<height) {
        //     offsetY = height-(parentMc.mv1.y+parentMc.mv1.getBounds().height);
        //     touchEndEnd = true;
        // } else {
        //     touchEndEnd = false;
        // }
        //         break;
        //     }
        // }

        pt_mc.y += offsetY;
        pt_mc.x += offsetX;

        if(_callback) {
            let touchPt = null;

            if(touched) {
                touchPt = parentMc.globalToLocal(e.stageX, e.stageY);
                touchPt.x = currStageX;
                touchPt.y = currStageY;
            }

            _callback(offsetX, offsetY, touchPt, { state: "pressmove"});
        }

        // mc.y+=offsetY;
        // if(touchEndStart||touchEndEnd) {
        //     if(!parentMc.dispatchEventMousedown&&touched) {
        //         var event = new createjs.Event("mousedown");
        //         let pt = parentMc.localToGlobal(pt_mc.x, pt_mc.y);
        //
        //         event.stageX = pt.x;
        //         event.stageY = pt.y;
        //
        //         exportRoot.main.dispatchEvent(event);
        //         parentMc.dispatchEventMousedown = true;
        //     }
        // }
    }

    function handleEnd (e) {
        parentMc.removeEventListener("pressup", handleEnd);
        parentMc.removeEventListener("pressmove", handleMove);

        touched = false;
        stageX=0;
        stageY=0;

        //speed = 0;
        timeStamp = 0;

        if(parentMc.dispatchEventMousedown) {
            exportRoot.main.dispatchEvent("pressup");
        }

        parentMc.dispatchEventMousedown = false;

        if(_callback) {
            let result = _callback(null, null, null, { state: "pressup"});

            if(result!=null&&result==false) {
                speedY = 0;
                speedX = 0;
            }
        }
    }
}

function createInput_1 (mc_input, {textAlign, color, placeholder, focus=true, lisentEvent=true}) {
    let pt = mc_input.parent.localToGlobal(mc_input.x, mc_input.y)
    let width = mc_input.getBounds().width / canvasScale;
    let height = mc_input.getBounds().height / canvasScale;

    if (!mc_input.input) {
        let input = $("<div class='input-box'><input type='text' "+
            "name='"+mc_input.name+"' "+
            (placeholder!=null ? "placeholder='"+placeholder+"' ":"")+
            " style='" +
            (textAlign != null ? "text-align: " + textAlign + ";" : "") +
            (color != null ? "color: " + color + ";" : "")
            + "'></input></div>");

        $("body").append(input);

        input.attr("id", mc_input.name);
        mc_input.input = input;

        if(lisentEvent) {
            mc_input.input.find("input, textarea")[0].addEventListener("blur", function( event ) {
                mc_input.input.removeClass('show');
                if(mc_input.input.find("input, textarea").val()!="") {
                    let txt_val = new createjs.Text();
                    txt_val.font = "28px " + fontFamily;
                    txt_val.color = mc_input.input.find("input, textarea").css("color");
                    txt_val.textAlign = mc_input.input.find("input, textarea").css("text-align");
                    txt_val.text = mc_input.input.find("input, textarea").val();
                    txt_val.name = "txt_val";

                    switch (txt_val.textAlign) {
                        case "left": {
                            txt_val.x = 20;
                            txt_val.y = 22;
                            break;
                        }
                        case "center": {
                            txt_val.x = mc_input.getBounds().width / 2;
                            txt_val.y = (mc_input.getBounds().height - txt_val.getBounds().height) / 2;
                            break;
                        }
                    }

                    mc_input.addChild(txt_val)
                }
            }, true);
        }
    }

    mc_input.removeChild(mc_input.getChildByName("txt_val"));

    mc_input.input.css("top", (pt.y/stage.scaleX/canvasScale)+"px");
    mc_input.input.css("left", (pt.x/stage.scaleX/canvasScale)+"px");
    mc_input.input.css('width', width + 'px')
    mc_input.input.css('height', height + 'px');
    mc_input.input.addClass('show');

    if(focus) {
        mc_input.input.find("input").focus();
    }
}

function onScrollMc(mc, callback) {
    // 页面内长图滚动
    let touched = false, ticking = false;
    let startStageX=0, startStageY=0, stageX=0, stageY=0, speedX=0, speedY=0, timeStamp=0, currStageX=0, currStageY=0, currTimeStamp=0, speedUpdateTimeStamp=0;
    let pt_mc = null;

    let parentMc = mc.parent;
    let _callback = callback;

    parentMc.addEventListener("mousedown", handleStart);

    function handleStart(e) {
        touched = true;

        let pt = parentMc.globalToLocal(e.stageX, e.stageY);

        startStageX=pt.x;
        startStageY=pt.y;
        stageX = pt.x;
        stageY = pt.y;
        timeStamp = e.timeStamp;

        currStageX = startStageX;
        currStageY = startStageY;
        currTimeStamp = timeStamp;

        if(!parentMc.getChildByName("pt_mc")) {
            pt_mc = new lib.pt();
            pt_mc.name = "pt_mc";
            parentMc.addChild(pt_mc);
            pt_mc.mouseEnabled = false;
            pt_mc.visible = false;
        } else {
            pt_mc = parentMc.getChildByName("pt_mc")
        }

        pt_mc.x = pt.x;
        pt_mc.y = pt.y;

        if(_callback) {
            let touchPt = null;

            if(touched) {
                touchPt = parentMc.globalToLocal(e.stageX, e.stageY);
                touchPt.x = currStageX;
                touchPt.y = currStageY;
            }

            _callback(0, 0, touchPt, { state: "mousedown"});
        }

        parentMc.addEventListener("pressup", handleEnd);
        parentMc.addEventListener("pressmove", handleMove);

        if(!ticking) {
            parentMc.addEventListener("tick", onScorllTick);
            ticking = true;
        }

        e.stopPropagation();
    }

    function handleMove (e) {
        let t = e.timeStamp-timeStamp;
        let pt = parentMc.globalToLocal(e.stageX, e.stageY);

        if(parentMc.dispatchEventMousedown) {
            var event = new createjs.Event("pressmove");
            event.stageX = e.stageX;
            event.stageY = e.stageY;

            exportRoot.main.dispatchEvent(e);
        } else {
            e.stopPropagation();
        }

        currStageX = pt.x;
        currStageY = pt.y;
        currTimeStamp = e.timeStamp;
    }

    function onScorllTick(e) {
        if(parentMc.dispatchEventMousedown) {
            return;
        }

        if(!touched) {
            if(Math.abs(speedY)>0) {
                speedY += -speedY/10;

                if(Math.abs(speedY)<=0.01) {
                    speedY = 0;
                }
            }

            if(Math.abs(speedX)>0) {
                speedX += -speedX/10;

                if(Math.abs(speedX)<=0.01) {
                    speedX = 0;
                }
            }

            if(Math.abs(speedY)<=0&&Math.abs(speedX)<=0) {
                ticking = false;
                parentMc.removeEventListener("tick", onScorllTick);
            }
        } else {
            let t = currTimeStamp-timeStamp;

            if(t!=0) {
                speedY = (currStageY-stageY)/t;
                speedX = (currStageX-stageX)/t;
            } else {
                speedY = 0;
                speedX = 0;
            }
        }

        stageX = currStageX;
        stageY = currStageY;
        timeStamp=currTimeStamp;

        let offsetY = speedY*e.delta;
        let offsetX = speedX*e.delta;

        pt_mc.y += offsetY;
        pt_mc.x += offsetX;

        if(_callback) {
            let touchPt = null;

            if(touched) {
                touchPt = parentMc.globalToLocal(e.stageX, e.stageY);
                touchPt.x = currStageX;
                touchPt.y = currStageY;
            }

            _callback(offsetX, offsetY, touchPt, { state: "pressmove"});
        }
    }

    function handleEnd (e) {
        parentMc.removeEventListener("pressup", handleEnd);
        parentMc.removeEventListener("pressmove", handleMove);

        touched = false;
        stageX=0;
        stageY=0;

        //speed = 0;
        timeStamp = 0;

        if(parentMc.dispatchEventMousedown) {
            exportRoot.main.dispatchEvent("pressup");
        }

        parentMc.dispatchEventMousedown = false;

        if(_callback) {
            let result = _callback(null, null, null, { state: "pressup"});

            if(result!=null&&result==false) {
                speedY = 0;
                speedX = 0;
            }
        }
    }
}

function loadPageResources(page) {
    if(page.loader==null) {
        page.data.resourceMap = new Map();
        page.loader = new createjs.LoadQueue(false);
        page.loader.addEventListener("fileload", function(evt) {
            evt.item.state = 2;
            for (let i = 0; i < evt.item.mc_path.length; i++) {
                var path = evt.item.mc_path[i].split("/");
                var mv = page;

                for (let i = 0; i < path.length; i++) {
                    mv = mv[path[i]];
                }

                var resourceImg = page.data.resourceMap.get(evt.item.id);

                if(!resourceImg["asset_"+i]) {
                    let img = page.loader.getResult(evt.item.id);
                    resourceImg["asset_"+i] = new createjs.Bitmap(img);
                } else {
                    resourceImg["asset_"+i].parent.removeChild(resourceImg["asset_"+i]);
                }

                mv.addChild(resourceImg["asset_"+i]);
            }
        });

        page.parent.addEventListener("removed", e=>{
            e.remove();
            for (let i = 0; i < page.data.resourceImgs.length; i++) {
                for (let j = 0; j < 100; j++) {
                    if(page.data.resourceImgs[i]["asset_"+j]) {
                        page.data.resourceImgs[i]["asset_"+j].parent.removeChild(page.data.resourceImgs[i]["asset_"+j]);
                        page.data.resourceImgs[i]["asset_"+j].image = null;
                        delete page.data.resourceImgs[i]["asset_"+j];
                    } else {
                        break;
                    }
                }

                page.data.resourceImgs[i].state = 0;
            }

            page.loader.removeAll();
            delete page.loader;
        })
    }

    var load_count = 0;

    for (let i = 0; i < page.data.resourceImgs.length; i++) {
        let resourceImg = page.data.resourceImgs[i];

        if(!page.data.resourceMap.has(resourceImg.id)) {
            page.data.resourceMap.set(resourceImg.id, resourceImg)
        }

        if(!resourceImg.state||resourceImg.state==0) {
            resourceImg.state = 1;
            page.loader.loadFile(resourceImg);
            load_count++;
        } else {
            var event = new Event("fileload");
            event.item = resourceImg;
            page.loader.dispatchEvent(event);
        }
    }

    if(load_count<=0) {
        setTimeout(()=>{
            page.loader.dispatchEvent("complete");
        }, 300);
    } else {
        page.loader.loadManifest(page.data.resourceImgs);
    }

    return page.loader;
}

const maxStarSize = 30;

function getStar(bg) {
    if(!bg.getChildByName("star_0")) {
        var starSize = randomNum(10, maxStarSize);
        for (let i = 0; i < starSize; i++) {
            var x = randomNum(0, bg.getBounds().width);
            var y = randomNum(0, bg.getBounds().height);
            var type = randomNum(0, 10);
            var star;

            if(type<2) {
                star = new lib.star_2();
            } else {
                star = new lib.star();
                var alpha = randomNum(0, 1);
                star.alpha = alpha==0?0.37:1;
            }
            star.x = x;
            star.y = y;
            star.name = "star_"+i;
            bg.addChild(star);

            star.gotoAndPlay(randomNum(0, star.totalFrames-1))
        }
    }
}

function pageOrientationChange(e) {
    // 屏幕宽度
    let iw = window.innerWidth;
    // 屏幕高度
    let ih = window.innerHeight;

    var ratio = ih/iw;

    var w = lib.properties.width;
    var h = w*ratio;
    lib.properties.height = h;

    // console.log(mainPage.currPage.page.bg.getBounds());
    // console.log(mainPage.currPage.page.getBounds());
    // console.log(innerWidth, innerHeight)
    // console.log(lib.properties.width, lib.properties.height)
    // if(mainPage.currPage.page.bg.getBounds())

    switch (e.orientation) {
        case VERTICAL:{
            console.log("竖屏")
            // Toast("竖屏")

            if(mainPage.currPage) {
                console.log(lib.properties.width, lib.properties.height)

                let containerMask = new createjs.Shape();
                containerMask.width = lib.properties.width;
                containerMask.height = lib.properties.height;
                containerMask.graphics.beginFill("#ffffff").drawRect(0, 0, lib.properties.width, lib.properties.height);
                mainPage.currPage.page.mask = containerMask;

                mainPage.currPage.page.shadow = new createjs.Shape();

                mainPage.currPage.page.shadow.width = lib.properties.width;
                mainPage.currPage.page.shadow.height = lib.properties.height;
                mainPage.currPage.page.shadow.graphics.beginFill("#ffffff").drawRect(0, 0, lib.properties.width, lib.properties.height);
                mainPage.currPage.page.shadow.shadow = new createjs.Shadow("#303030", 0, 0, 50);

                let bounds_bg = mainPage.currPage.page.bg.getBounds();
                let scale = lib.properties.height/bounds_bg.height;

                if(scale*bounds_bg.width<lib.properties.width) {
                    scale = lib.properties.width/bounds_bg.width;
                }

                mainPage.currPage.page.bg.scaleY = mainPage.currPage.page.bg.scaleX = scale;

                mainPage.currPage.page.bg.y = lib.properties.height/2;
                mainPage.currPage.page.bg.x = lib.properties.width/2;

                mainPage.currPage.scale = 1;
                mainPage.currPage.rotation = 0;
                mainPage.currPage.y = 0;
                mainPage.currPage.x = 0;
            }
            break;
        }
        case HORIZONTAL:{
            console.log("横屏")
            // Toast("横屏")

            if(mainPage.currPage) {
                console.log(mainPage.currPage.getBounds());
                console.log(lib.properties.width, lib.properties.height)

                let scale = lib.properties.height/lib.properties.width
                mainPage.currPage.scale = scale;

                // 旋转mc
                mainPage.currPage.rotation = -90;
                mainPage.currPage.y = lib.properties.height;
                mainPage.currPage.x = 0;

                // leftMargin/mainPage.currPage.page.bg.getTransformedBounds().height*lib.properties.width;

                let lib_properties_width = lib.properties.width;
                let lib_properties_height =  lib.properties.width*lib.properties.width/lib.properties.height;

                let containerMask = new createjs.Shape();
                containerMask.width = lib.properties.width;
                containerMask.height = lib.properties.height;
                containerMask.graphics.beginFill("#ffffff").drawRect(0, 0, lib_properties_width, lib_properties_height);
                mainPage.currPage.page.mask = containerMask;

                mainPage.currPage.page.shadow = new createjs.Shape();

                mainPage.currPage.page.shadow.width = lib_properties_width;
                mainPage.currPage.page.shadow.height = lib_properties_height;
                mainPage.currPage.page.shadow.graphics.beginFill("#ffffff").drawRect(0, 0, lib_properties_width, lib_properties_height);
                mainPage.currPage.page.shadow.shadow = new createjs.Shadow("#303030", 0, 0, 50);
            }
            break;
        }

    }
}

function pageDestroy(e) {
    var page = e.page.page;
    page.destoried = true;

    createjs.Text = that.create_text;

    switch (e.pageId) {
        case 2:{
            App.user.name.show = false;
            App.user.phone.show = false;
            App.user.address.show = false;
            break;
        }
    }
    delete e.page.page;
    delete e.page;
}

function main_page(evt, comp, pageId) {
    lib = comp.getLibrary();
    this.currPage = null;
    this.currPageNum = pageId;
    this.nextPage = null;
    this.nextPageNum = null;

    pageUtil.addEventListener("pageInited", onPageInited);
    pageUtil.addEventListener("pageUpdated", pageUpdated);
    pageUtil.addEventListener("pageDestroy", pageDestroy);
    pageUtil.addEventListener("orientationChange", pageOrientationChange);

    this.onInited = ()=>{
        var page = pageUtil.getPage(this.currPageNum);
        exportRoot.main.addChild(page);
        this.currPage = page;
        page.onUpdate();
    }

    return this;
}

function closeDlg() {
    exportRoot.dlgs.gotoAndStop(0);
}

function openDlg(dlgId, callback) {
    exportRoot.dlgs.gotoAndPlay(1);
    exportRoot.dlgs.bg.scaleY = lib.properties.height/exportRoot.dlgs.bg.getBounds().height;

    switch (dlgId) {
        case 1:{
            // 助力
            exportRoot.dlgs.body.mc.txt.gotoAndStop(0);
            exportRoot.dlgs.body.mc.bg.gotoAndStop(0);
            exportRoot.dlgs.btn_enter.mc.gotoAndStop(0);
            exportRoot.dlgs.btn_enter.visible = true;
            exportRoot.dlgs.btn_close.visible = true;
            exportRoot.dlgs.btn_close.x=662
            break;
        }
        case 2:{
            // 助力成功
            exportRoot.dlgs.body.mc.txt.gotoAndStop(1);
            exportRoot.dlgs.body.mc.bg.gotoAndStop(0);
            exportRoot.dlgs.btn_enter.mc.gotoAndStop(1);
            exportRoot.dlgs.btn_enter.visible = true;
            exportRoot.dlgs.btn_close.visible = true;
            exportRoot.dlgs.btn_close.x=662
            break;
        }
        case 3:{
            // 进度显示
            exportRoot.dlgs.body.mc.txt.gotoAndStop(2);
            exportRoot.dlgs.body.mc.bg.gotoAndStop(1);
            exportRoot.dlgs.btn_enter.visible = false;
            exportRoot.dlgs.btn_close.visible = false;
            exportRoot.dlgs.btn_close.x=662
            break;
        }
        case 4:{
            // 分享
            exportRoot.dlgs.body.mc.txt.gotoAndStop(3);
            exportRoot.dlgs.body.mc.bg.gotoAndStop(0);
            exportRoot.dlgs.btn_enter.visible = false;
            exportRoot.dlgs.btn_close.visible = true;
            exportRoot.dlgs.btn_close.x=130;
            break;
        }
    }

    exportRoot.dlgs.btn_close.addEventListener("click", e=>{
        exportRoot.dlgs.gotoAndStop(0);

        if(callback) {
            setTimeout(()=>{
                callback({cancel: true});
                callback = null;
            }, 200);
        }
    });

    exportRoot.dlgs.btn_enter.addEventListener("click", e=>{
        exportRoot.dlgs.gotoAndStop(0);

        if(callback) {
            setTimeout(()=>{
                callback({enter: true});
                callback = null;
            }, 200);
        }
    });
}

let nextPageId;
let prevPageNum=0;

function openPage(pageId, { prev, params }={}) {
    if(nextPageId==pageId) {
        return;
    }

    nextPageId = pageId;
    var page = pageUtil.getPage(pageId, {params: params});
    // page.onUpdate();
    page.alpha = 0;

    if(prev) {
        prevPageNum = 0;
    } else {
        prevPageNum = mainPage.currPageNum;
    }

    switch (PAGE_CHANGE_MODEL) {
        case HORIZONTAL:{
            // 水平
            page.x = lib.properties.width;
            page.y = 0;

            if(prev) {
                page.x = -lib.properties.width;
            }
            break
        }
        case VERTICAL: {
            // 垂直
            page.x = 0;
            page.y = lib.properties.height;

            if(prev) {
                page.y = -lib.properties.height;
            }
            break
        }
    }
    exportRoot.main.addChild(page);

    createjs.Tween.get(mainPage.currPage, {override:true}).to({scaleX:0, scaleY:0, alpha:0}, 400).call(e=>{
        var page = e.target;
        exportRoot.main.removeChild(page);
        page.onDestroy();
    }).addEventListener("change", (event)=>{
        event.target.target.x = (lib.properties.width-lib.properties.width*event.target.target.scaleX)/2;
        event.target.target.y = (lib.properties.height-lib.properties.height*event.target.target.scaleY)/2;
    })

    createjs.Tween.get(page, {override:true}).to({scaleX:1, scaleY:1, alpha:1, x:0, y:0}, 400).call(e=>{
        var page = e.target;
        mainPage.currPage = page;
        mainPage.currPageNum = pageId;
        nextPageId = null;
        page.onUpdate();
    })
}
